package com.shg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shg.domain.LoginUser;
import com.shg.domain.User;
import com.shg.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @DESCRIPTION:
 * 自定义一个UserDetailService的实现类并把这个实现类加入到容器中，替换掉SpringSecurity框架自定义的实现类InMemoryUserDetailsManager
 * 那么问题来了，为什么我自定义一个UserDetailService的实现类之后，框架就会自动使用我这个实现类呢？框架是怎么做到的呢？
 * 此时就应该想到SpringBoot中的自动配置原理，在 public class UserDetailsServiceAutoConfiguration 这个配置类的头上，可以发现有如下：
 * @AutoConfiguration
 * @ConditionalOnClass({AuthenticationManager.class})
 * @ConditionalOnBean({ObjectPostProcessor.class})
 * @ConditionalOnMissingBean(
 *     value = {AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class, AuthenticationManagerResolver.class},
 *     type = {"org.springframework.security.oauth2.jwt.JwtDecoder", "org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector", "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository", "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository"}
 * )
 * 如上：在@ConditionalOnMissingBean里面有 UserDetailsService.class，说明当容器中没有 UserDetailsService的实现类时，这个配置类才生效，现在我自己写了一个
 * UserDetailsService的实现类，并且也放到容器中了，那么自动配置类不生效，容器中也就没有了InMemoryUserDetailsManager这个类
 *
 * @USER: shg
 * @DATE: 2023/5/5 10:17
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User userFromDB = userMapper.selectOne(wrapper);
        if(Objects.isNull(userFromDB)){
            throw new RuntimeException("用户名或密码错误");
        }

        // todo 查询用户权限信息

        // 把数据封装成UserDetails对象并返回

        return new LoginUser(userFromDB);
    }
}
